package com.table;

import com.appclient.ControlledScreen;
import com.appclient.DaoInstanceEnum;
import com.appclient.ScreensController;
import com.carpark.ejb.Model.PaymentsModel;
import com.carpark.ejb.Model.ReceivablesModel;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import popup.PopupController;

/**
 *
 * @author Sawior
 */
public class ReceivablesTableController implements Initializable, ControlledScreen {

    private ScreensController myController;
    @FXML
    private TextField filterField;
    @FXML
    private TableView<ReceivablesModel> recTable;
    @FXML
    private TableColumn<ReceivablesModel, String> pass;
    @FXML
    private TableColumn<ReceivablesModel, String> start;
    @FXML
    private TableColumn<ReceivablesModel, String> deadline;
    @FXML
    private TableColumn<ReceivablesModel, String> cost;
    @FXML
    private Button pay;
    @FXML
    private ChoiceBox payType;  
    private ObservableList<ReceivablesModel> masterData = FXCollections.observableArrayList();
    private ObservableList<ReceivablesModel> filteredData = FXCollections.observableArrayList();

    @Override
    public void initialize(URL url, ResourceBundle rb) {
    }

    @Override
    public void setScreenParent(ScreensController screenParent) {
        myController = screenParent;
        initialize();

    }

    public ReceivablesTableController() {
        loadData();
        masterData.addListener(new ListChangeListener<ReceivablesModel>() {
            @Override
            public void onChanged(ListChangeListener.Change<? extends ReceivablesModel> change) {
                updateFilteredData();
            }
        });
    }
    
    private void loadData() {
        masterData = FXCollections.observableArrayList();
        filteredData = FXCollections.observableArrayList();
        List<ReceivablesModel> data = DaoInstanceEnum.INSTANCE.getDao().getAllReceivable();
        for (ReceivablesModel rec : data) {
            if(!isPayed(rec)) {
                masterData.add(rec);
            }
        }

        filteredData.addAll(masterData);
    }
    
    private boolean isPayed(ReceivablesModel rec) {
        List<PaymentsModel> payed = DaoInstanceEnum.INSTANCE.getDao().getAllPayments();
        for (PaymentsModel paymentsModel : payed) {
            if(paymentsModel.getReceivableId().getReceivableId() == rec.getReceivableId()){
                return true;
            }
        }
        return false;
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        pass.setCellValueFactory(
                new PropertyValueFactory<ReceivablesModel, String>("parkingPassId"));
        start.setCellValueFactory(
                new PropertyValueFactory<ReceivablesModel, String>("creationDate"));
        deadline.setCellValueFactory(
                new PropertyValueFactory<ReceivablesModel, String>("payDeadline"));
        cost.setCellValueFactory(
                new PropertyValueFactory<ReceivablesModel, String>("amount"));

        recTable.setItems(filteredData);

        filterField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {
                updateFilteredData();
            }
        });
    }

    private void updateFilteredData() {
        filteredData.clear();

        for (ReceivablesModel receivable : masterData) {
            if (matchesFilter(receivable)) {
                filteredData.add(receivable);
            }
        }
        reapplyTableSortOrder();
    }

    private boolean matchesFilter(ReceivablesModel rec) {
        String filterString = filterField.getText();
        if (filterString == null || filterString.isEmpty()) {
            return true;
        }
        String lowerCaseFilterString = filterString.toLowerCase();

        if (rec.getParkingPassId().getParkingPassId().toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (rec.getCreationDate().toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (rec.getPayDeadline().toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        Double amount = rec.getAmount();
        if (amount.toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }

        return true;
    }

    private void reapplyTableSortOrder() {
        ArrayList<TableColumn<ReceivablesModel, ?>> sortOrder = new ArrayList<>(recTable.getSortOrder());
        recTable.getSortOrder().clear();
        recTable.getSortOrder().addAll(sortOrder);
    }

    @FXML
    private void makeChoice(ActionEvent event) {
        if (event.getSource() == pay) {
            if(!convertPayType().equals("")) {
                ReceivablesModel rec = recTable.getSelectionModel().getSelectedItem();
                PaymentsModel payment = new PaymentsModel(new Date(), convertPayType());
                payment.setReceivableId(rec);
                DaoInstanceEnum.INSTANCE.getDao().addPayment(payment);
                createPopup("Wykonano płatność");
                filterField.setText("");
                loadData();
            }
            else {
                payType.setValue("Wybierz typ");
                createPopup("Wybierz typ płatności");
            }
        }
    }
    
    private void createPopup(String text) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("popup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Informacja");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);

            PopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            controller.setPopupText(text);
            dialogStage.showAndWait();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private String convertPayType(){
        if(this.payType.getValue() == null){
            return "";
        }
        if(this.payType.getValue().equals("Gotówka")) {
            return "Cash";
        }
        if(this.payType.getValue().equals("Karta kredytowa")) {
            return "CreditCard";
        }
        if(this.payType.getValue().equals("Przelew")) {
            return "Transfer";
        }
        return "";
        
    }
}
